#coding:utf8

import re
from django.template import Library
from ..lib import fun
from django.utils.safestring import mark_safe
import urllib.parse
 
register = Library()

@register.filter
def json(st):
    return fun.parseJson(st)

@register.filter
def getMapStr(key, st):
    return fun.parseJson(st).get(key, '')

@register.filter
def getMap(key, _d):
    return _d.get(key, '')

@register.filter
def getIndex(arr, _d):
    return arr[_d]

@register.filter
def int(key):
    return fun.parseInt(key)

@register.filter
def join(arr, j):
    if isinstance(arr, str):
        return arr
    return j.join(map(str, arr))

@register.filter
def inArray(val, arr):
    return val in arr

@register.filter
def decimal(value, width=2):
    value = fun.parseFloat(value)  
    return round(value, width)  

@register.filter
def times(value, num):
    return value * num

@register.simple_tag
def division(value, value2, width=2):
    return round(fun.parseFloat(value)/value2, width)

@register.filter
def rmb(value):
    return fun.parseRmb(value)

@register.filter
def truncate(value, length=10):
    length = int(length)

    if len(value) > length:
        return value[0:int(length)] + '...'
    return value

@register.filter
def format(num):
    try:
        return format(num, ',')
    except:
        num = str(num)
        pattern = r'(\d+)(\d{3})((,\d{3})*)'
        while True:
            num,count = re.subn(pattern,r'\1,\2\3',num)
            if count == 0:
                break
        return num

@register.filter
def hideMobile(mobile):
    if mobile == '' or mobile is None:
        return '' 
    if len(mobile) < 11:
        return mobile
    return '%s****%s'%(mobile[0:3], mobile[7:])

@register.filter
def hideName(name):
    if name == '' or name is None:
        return '' 
    return '%s**'%name[0:1]

@register.filter
def hideEmail(email):
    if email == '' or email is None:
        return ''

    arr = email.split('@')
    if len(arr) < 2:
        return email

    if re.match('^\d{11}$', arr[0]) is not None:
        prefix = '%s****%s'%(arr[0][0:3], arr[0][7:])
    else:
        prefix = arr[0]
    
    return '%s@%s'%(prefix, arr[1])

@register.filter
def split(value, key):
    if value is None:
        return []
    return value.split(key)

@register.filter
def reduce(val1, val2):
    return val1 - val2

@register.filter
def division_2(val):
    return val%2

@register.simple_tag
def inputHtml(val, inputName, labelTxt, inputType='text', inputSm=4, labelSm=1, isRequired=0, remark='', remarkPostion='label', other=''):
    requiredTxt = '<span style="color:red;">*</span>' if isRequired else ''
    required = "required" if isRequired else ''
    if inputType == 'image':
        url, ratio, fsize = '', '', ''
        if isinstance(val, dict):
            url, ratio, fsize = val.get('url', ''), val.get('ratio', ''), val.get('fsize', '')
        elif isinstance(val, str):
            url = val
            
        inputHtml = """
            <img onclick="edit_image($(this), '{name}');" src="{url}" class="upload-img-click" alt="无图" onerror="this.src='/static/images/default.png';">
            <input type="hidden" name="{name}" value="{url}" {required} {other} />
            <input type="hidden" name="{name}_ratio" value="{ratio}"/>
            <input type="hidden" name="{name}_fsize" value="{fsize}"/>
        """.format(name=inputName, url=url, ratio=ratio, fsize=fsize, required=required, other=other)
    elif inputType == 'video':
        inputHtml = """
            <video src="{val}" controls="controls" style="max-width:75%;max-height:100px;"/>
            <input type="hidden" name="{name}" value="{val}" {required} {other} />
            <input type="hidden" name="{name}_fsize" value=""/>

            <button type="button" class="btn-link" title="编辑" onclick="edit_video($(this).siblings('video'), '{name}');"><i class="fa fa-edit"></i></button>
            <button type="button" class="btn-link" title="播放" onclick="window.open($(this).siblings('video').attr('src'), '_blank');">
                <i class="glyphicon glyphicon-play"></i>
            </button>
       """.format(name=inputName, val=val, required=required, other=other)
    elif inputType == 'textarea':
        inputHtml = """
            <textarea class="form-control" name="{name}"  placeholder="{placeholder}" {required} {other}>{val}</textarea>
        """.format(name=inputName, val=val, required=required, placeholder=labelTxt, other=other)
    elif inputType == 'number':
        inputHtml = """
        <input type="number" class="form-control" name="{name}" placeholder="{placeholder}" value="{val}" {required} {other} min="0">
        """.format(inputType=inputType, name=inputName, placeholder=labelTxt, val=val, required=required, other=other)
    elif inputType == 'datesingle':
        inputHtml = """
        <input type="text" class="form-control datesingle" name="{name}" placeholder="{placeholder}" value="{val}" {required} {other} readonly>
        """.format(inputType=inputType, name=inputName, placeholder=labelTxt, val=val, required=required, other=other)
    else:
        inputHtml = """
        <input type="{inputType}" class="form-control" name="{name}" placeholder="{placeholder}" value="{val}" {other} {required}>
        """.format(inputType=inputType, name=inputName, placeholder=labelTxt, val=val, required=required, other=other)

    remarkHtml = '<span class="help-block">{remark}</span>'.format(remark=remark) if remark else ''
    if remarkPostion == 'label':
        labelRemark = remarkHtml
        inputRemark = ''
    else:
        inputRemark = remarkHtml
        labelRemark = ''

    html = """
        <label class="control-label col-sm-{labelSm}">{requiredTxt}{labelTxt}{labelRemark}</label>
        <div class="col-sm-{inputSm}">{inputHtml}{inputRemark}</div>
        """.format(labelSm=labelSm, inputSm=inputSm, labelTxt=labelTxt, requiredTxt=requiredTxt,
                inputHtml=inputHtml, labelRemark=labelRemark, inputRemark=inputRemark)
    return mark_safe(html)

@register.filter
def urlAddQuery(url, queryDict):
    if '?' in url:
        return url+ '&'+ urllib.parse.urlencode(queryDict)
    return url+ '?'+ urllib.parse.urlencode(queryDict)

@register.filter
def quote(st, st2=''):
    return urllib.parse.quote_plus(st+st2)

@register.filter
def replaceLine(value):
    value = str(value).replace('\r', r'\r').replace('\n', r'\n')
    return value

@register.filter
def imgRatioFsize(url, ratio='', fsize=''):
    return {'url': url, 'ratio': ratio, 'fsize': fsize}

@register.filter
def watermark(imgUrl, request):
    if imgUrl[imgUrl.rfind('.'):].lower() not in ['.jpg', '.jpeg', '.png', '.gif', '.bmp']:
        return imgUrl

    import base64
    txt = request.user.first_name+request.session.get('mobile')[-4:]
    txt = base64.b64encode(txt.encode('utf-8'))
    txt = txt.decode('utf-8').replace('=', '').replace('+', '-').replace('/', '_')
    return imgUrl+'?x-oss-process=image/watermark,text_{txt},fill_1,rotate_15,t_10'.format(txt=txt)
